import { defineStore } from 'pinia'
import { getToken, setToken, removeToken, getUser, setUser, removeUser } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    userInfo: getUser(),
    permissions: [],
    roles: []
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    userName: (state) => state.userInfo?.username || '',
    userRole: (state) => state.userInfo?.role?.name || '',
    avatar: (state) => state.userInfo?.avatar || ''
  },

  actions: {
    // 登录
    async login(loginForm) {
      try {
        const response = await login(loginForm)
        if (!response.success) {
          throw new Error(response.msg || '登录失败')
        }
        
        // 从响应中正确提取数据
        const data = response.data
        this.token = data.token
        this.userInfo = data
        
        setToken(data.token)
        setUser(data)
        
        return response
      } catch (error) {
        throw error
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await getUserInfo()
        const user = response.data
        
        this.userInfo = user
        this.permissions = user.permissions || []
        this.roles = user.roles || []
        
        setUser(user)
        
        return user
      } catch (error) {
        throw error
      }
    },

    // 初始化用户信息
    async initUserInfo() {
      if (this.token && !this.userInfo) {
        try {
          await this.getUserInfo()
        } catch (error) {
          this.logout()
        }
      }
    },

    // 登出
    logout() {
      this.token = ''
      this.userInfo = null
      this.permissions = []
      this.roles = []
      
      removeToken()
      removeUser()
    },

    // 检查权限
    hasPermission(permission) {
      return this.permissions.includes(permission)
    },

    // 检查角色
    hasRole(role) {
      if (!this.roles || this.roles.length === 0) {
        return false
      }

      // 如果roles是字符串数组
      if (typeof this.roles[0] === 'string') {
        return this.roles.includes(role)
      }

      // 如果roles是对象数组
      return this.roles.some(r => r.name === role || r.code === role || r.roleCode === role)
    },

    // 检查是否是超级管理员
    isSuperAdmin() {
      return this.hasRole('SUPER_ADMIN') || this.hasRole('super_admin') || this.hasRole('超级管理员')
    }
  }
})
